package com.kabu;

/**
 * @author jiawuwei
 * @Copyright: Copyright (c) 兆日科技股份有限公司  2020
 * @date 2020/5/20,17:00
 * cpu缓存导致的可见性问题、线程切换带来的原子性问题: 待解决
 */
public class ThreadVisible {
    static long count = 0;

    private void add() {
        int idx = 0;
        while (idx++ < 30000000L) {
            count += 1;
        }
        System.out.println(Thread.currentThread().getName()+" "+count);
    }

    public static long calc() throws InterruptedException {
        final ThreadVisible test = new ThreadVisible();
        // 创建两个线程，执行add()操作
        Thread th1 = new Thread(()->{
            test.add();
        });
        Thread th2 = new Thread(()->{
            test.add();
        });
        Thread th3 = new Thread(()->{
            test.add();
        });
        // 启动两个线程
        th1.start();
        th2.start();
        th3.start();
        // 等待两个线程执行结束
        th1.join();
        th2.join();
        th3.join();
        return count;
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(calc());
    }
}
